/*
 * graph2D
 * Copyright (c) 2009 Shun Moriya <shun@mnu.sakura.ne.jp>
 *
 * The MIT License
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "desktop.h"
#include "dialog.h"
#include <cstring>
#include <string>

namespace Graph2D
{
	Dialog::Dialog()
	{
		setType(TYPE_DIALOG);

		selected = -1;
		setSize(Desktop::getInstance().getSize() * 0.33333333f);
	}

	/*!
	 * @param[in]	s		開始ポインタ
	 * @param[in]	e		終了ポインタ
	 * @param[in]	index	インデックス番号
	 */
	void Dialog::add(const char* s, const char* e, const int index)
	{
		size_t length = (size_t)(e - s);

		char* text = static_cast<char*>(alloca(length + 1));
		memcpy(text, s, length);
		text[length] = '\0';
		addContents(std::string(text), index);
	}

	/*!
	 * @param[in]	message		ダイアログ表示メッセージ。改行ごとに１選択文になります。
	 * @retval		true		成功
	 * @retval		false		失敗
	 */
	bool Dialog::initialize(const std::string& message)
	{
		clear();

		int index = 0;
		char* s = const_cast<char*>(message.c_str());
		char* e = s;

		while(*e != '\0')
		{
			if(*e == '\n')
			{
				add(s, e, index);

				index++;
				e++;
				s = e;
			}
			else
			{
				e++;
			}
		}

		add(s, e, index);

		// デスクトップの中心に設定(仮)
		const Vector2 center = (Desktop::getInstance().getSize() * 0.5f) - (getSize() * 0.5f);
		setPosition(center);

		selected = -1;

		return true;
	}

	bool Dialog::compare(const Dialog& other) const
	{
		if(!super::compare(other))
			return false;

		if(selected != other.selected)
			return false;

		return true;
	}
}
